<?php

class MsggIhuyi extends MsggChannelBase
{
    const REST_URL = 'http://api.vm.ihuyi.com/webservice';
    const SUCCESS_RESP_CODE ='2';

    const TYPE_SMS = 'sms';
    const TYPE_CALL = 'call';

    const ERROR_CODE_FAIL = 1;

    private static $_conf = array();

    public static function sms($params = array(), $conf = array())
    {
        $result = array('code' => self::ERROR_CODE_FAIL, 'msg' => 'ihuyi can\'t send sms');
        return $result;
    }

    public static function call($params = array(), $conf = array())
    {
        static::$_conf = $conf;
        $result = array('code' => 0, 'msg' => '', 'data' => array(), 'ext' => array());
        $appid = static::getConf('APPID');
        $apikey = static::getConf('APIKEY');
        $mobile = $params['phone'];
        $content = $params['media']['ext_ihuyi'];
        $time = time();
        try {
            $password = self::getPassword($appid, $apikey, $mobile, $content, $time);
            $url = self::getUrl(self::TYPE_CALL);
            $postdata = array(
                'account' => $appid,
                'password' => $password,
                'mobile' => $mobile,
                'content' => $content,
                'time' => $time,
                'format' => 'json',
            );
            $resp = self::curlApi($url, $postdata);
            $result['data'] = $resp;
            $result['ext']['id'] = empty($resp['voiceid']) ? null : $resp['voiceid'];
            $result['ext']['status'] = MsggCall::STATUS_SUCCESS;
        } catch (Exception $e) {
            //gen result
            $result['code'] = $e->getCode();
            $result['msg'] = $e->getMessage();
            $result['ext']['status'] = MsggCall::STATUS_ERROR;
        }
        //return result
        $result['ext']['class']=self::class;
        return $result;
    }

    private static function curlApi($url, $postdata = array(), $options = array())
    {
        try {
            $headers = array(
                'Accept' => 'application/json;',
            );
            $try = self::getConf('try', 2);
            while ($try) {
                $try--;
                $cres = Curl::post($url, $postdata, $options, $headers);
                if ($cres['err']) {
                    if ($try) {
                        continue;
                    }
                    throw new Exception('CurlErr:' . $cres['err'], self::ERROR_CODE_FAIL);
                }
                if (empty($cres['content'])) {
                    if ($try) {
                        continue;
                    }
                    throw new Exception('response content empty', self::ERROR_CODE_FAIL);
                }
                if (!($resp = json_decode($cres['content'], true))) {
                    if ($try) {
                        continue;
                    }
                    throw new Exception('response content decode fail:' . $cres['content'], self::ERROR_CODE_FAIL);
                }
                $respCode = isset($resp['code']) ? $resp['code']: null;
                if ($respCode != self::SUCCESS_RESP_CODE) {
                    if ($try) {
                        continue;
                    }
                    throw new Exception('response respCode abnormal:' . $cres['content'], self::ERROR_CODE_FAIL);
                }
                return $resp;
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), self::ERROR_CODE_FAIL);
        }
    }

    private static function getUrl($type = self::TYPE_SMS)
    {
        switch ($type) {
            case self::TYPE_CALL:
                return self::REST_URL . "/voice.php?method=Submit";
                break;
            case self::TYPE_SMS:
            default:
                return '';
                break;
        }
    }

    private static function getPassword($appid, $apikey, $mobile, $content, $time)
    {
        $time = empty($time) ? time() : $time;
        if (empty($appid) || empty($apikey) || empty($mobile) || empty($content)) {
            throw new Exception('ihuyi getPassword params invalidate', self::ERROR_CODE_FAIL);
        }
        return $password = md5($appid . $apikey . $mobile . $content . $time);
    }

    public static function getConf($name, $default = null)
    {
        return isset(static::$_conf[$name]) ? static::$_conf[$name] : $default;
    }

    public static function refreshStatus(MsggChannelLog $channelLog)
    {
        // TODO: Implement refreshStatus() method.
        if (!empty($channelLog) && $channelLog->type) {
            switch ($channelLog->type) {
                default:
                case MsggItem::TYPE_SMS:
                   return parent::refreshStatus($channelLog);
                    break;
                case MsggItem::TYPE_CALL:
                    return $channelLog->ext_status;
                    break;
            }
        }
        return parent::refreshStatus($channelLog);
    }
}